import "./index.less";
import { BasicForm, useForm, FormSchema } from "@/components/Form";
import Toolbar from "@/components/ViewComponents/Toolbar";
import { useTranslation } from "react-i18next";
import { patientsGet, patientsUpdate, patientsCreate, systemDeptTree } from "@/api/MedicalExamination";
import { useEffect, useRef, useState } from "react";
import { message } from "antd";
import { BasicTree } from "@/components/Tree";
import LogoImg from "@/assets/images/logo.png";

export default function self_registration() {
	const { t } = useTranslation();

	const isOldPatient = useRef(false);
	const patientId = useRef("");
	const formSchema: FormSchema[] = [
		{
			label: t("patientBasic.patient_code"),
			field: "patCardno",
			component: "Input",
			required: true,
			componentProps: {
				onChange: (e: ChangeEvent) => {
					if (e.target.value) getPatientInfo(e.target.value);
				}
			}
		},
		{
			label: t("patientBasic.citizen_id"),
			field: "citizenId",
			component: "Input"
		},
		{
			label: t("patientBasic.full_name"),
			field: "fullName",
			component: "Input"
		},
		{
			label: t("patientBasic.birthday"),
			field: "birthday",
			component: "DatePicker",
			componentProps: {
				format: "YYYY-MM-DD"
			}
		},
		{
			label: t("patientBasic.age"),
			field: "age",
			component: "Input"
		},
		{
			label: t("patientBasic.gender"),
			field: "gender",
			component: "Select",
			componentProps: {
				options: [
					{
						label: "female",
						value: 0
					},
					{
						label: "male",
						value: 1
					}
				]
			}
		},
		{
			label: t("felix_ui.reg_for_exam"),
			field: "regForExam",
			component: "Input"
		},
		{
			label: t("patientBasic.pat_address"),
			field: "patAddress",
			component: "Input"
		},
		{
			label: t("patientBasic.pat_type"),
			field: "patType",
			component: "Select",
			componentProps: {
				options: [
					{
						label: "new patient",
						value: "1"
					},
					{
						label: "old patient",
						value: "2"
					}
				]
			}
		}
	];
	const [registerForm, { setFieldsValue, validateFields, resetFields }] = useForm({
		schemas: formSchema,
		showActionButtonGroup: false,
		labelWidth: 150,
		baseColProps: { span: 24 }
	});

	const [treeData, setTreeData] = useState([]);

	/** Function */

	const handlerAction = (key: string) => {
		switch (key) {
			case "continue":
				break;
			case "save":
				handlerSubmit();
				break;
		}
	};

	/** Request */

	const getDeptTree = async () => {
		const res = await systemDeptTree({});
		setTreeData(res);
	};
	const getPatientInfo = async (patCardno: string) => {
		const res = await patientsGet({ patCardno });
		if (res) {
			isOldPatient.current = true;
			patientId.current = res.patientId;
			setFieldsValue({
				...res,
				patAddress: `${res.addrProvince}${res.addrCity}${res.addrDistrict}${res.addrCommune}${res.addrWard}${res.addrHouseno}`,
				patType: "2"
			});
		} else {
			isOldPatient.current = false;
			resetFields(formSchema.slice(1, formSchema.length).map((item: any) => item.field));
			setFieldsValue({
				patType: "1"
			});
		}
	};

	const handlerSubmit = async () => {
		const loading = message.loading(t("common.saveLoading"));
		try {
			const values = await validateFields();
			if (values.birthday) values.birthday = values.birthday.split(" ")[0];
			values.patientId = patientId.current;
			await (isOldPatient.current ? patientsUpdate(values) : patientsCreate(values));
			loading();
			message.success(t("common.saveSuccessText"));
		} catch (err) {
			console.log(err);
			loading();
			message.error(err);
		}
	};

	/** Effect */

	useEffect(() => {
		getDeptTree();
	}, []);

	return (
		<div className="self_registration page">
			<div className="content page-content">
				<div className="content-header block">
					<img className="content-header-logo" src={LogoImg} />
					<div>
						<div className="content-header-title"> {t("MedicalExamination.selfRegistration.title")}</div>
						<div className="content-header-subtitle">{t("MedicalExamination.selfRegistration.subtitle")}</div>
					</div>
				</div>
				<div className="content-main mt-2">
					<div className="content-main-dept block">
						<div className="block-label">1.{t("MedicalExamination.selfRegistration.department")}</div>
						<BasicTree clickRowToExpand={false} treeData={treeData} fieldNames={{ key: "id", title: "name" }} />
					</div>
					<div className="content-main-form block ml-2">
						<div className="block-label">2.{t("MedicalExamination.selfRegistration.registration")}</div>
						<BasicForm register={registerForm}></BasicForm>
					</div>
				</div>
			</div>
			<Toolbar btnList={[{ key: "save" }]} action={handlerAction} />
		</div>
	);
}
